#pragma once
#include <iostream>
#include <pthread.h>

namespace myMutex
{
    class Mutex
    {
    public:
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;
        Mutex()
        {
            int n = pthread_mutex_init(&_mylock, NULL);
            if (n != 0)
            {
                std::cerr << "Mutex initialization failed" << std::endl;
            }
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mylock);
            if (n != 0)
            {
                std::cerr << "Mutex destruction failed" << std::endl;
            }
        }

        void lock()
        {
            int n = pthread_mutex_lock(&_mylock);
            if (n != 0)
            {
                std::cerr << "Mutex lock failed" << std::endl;
            }
        }

        void unlock()
        {
            int n = pthread_mutex_unlock(&_mylock);
            if (n != 0)
            {
                std::cerr << "Mutex unlock failed" << std::endl;
            }
        }

    private:
        pthread_mutex_t _mylock;
    };

    class MutexGuard
    {
    public:
        MutexGuard(Mutex &mutex) : _mutex(mutex)
        {
            _mutex.lock();
        }
        ~MutexGuard()
        {
            _mutex.unlock();
        }

    private:
        Mutex &_mutex;
    };
} // namespace Mutex
